package v1

import (
	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"main/middlewares/public/cache"
	"main/middlewares/public/db"
	"main/middlewares/public/jwt"
	"main/middlewares/public/status"
	"main/middlewares/public/util"
	"main/models"
	"strings"
	"time"
)

// LoginResult 登录结果结构
type LoginResult struct {
	Token    string        `json:"token"`
	User     models.H_user `json:"user"`
	Password string        `json:"-"`
}

// @Summary 登录
// @Description 登录系统
// @Tags 权限
// @Produce  json
// @Param   username     query    string  true        "用户名"
// @Param   password     query    string  true        "密码,明文或秘钥"
// @Success 200  {object} LoginResult
// @Failure 201
// @router /api/v1/Login/ [post]
func Login(c *gin.Context) {

	username := strings.TrimSpace(c.PostForm("username"))
	password := strings.TrimSpace(c.PostForm("password"))
	CacheKey := username + "_user"

	if UserCache := cache.Gmaps.Get(CacheKey); UserCache != nil {
		DataCache, ok := UserCache.(LoginResult)
		if ok {
			if(DataCache.Password==password){
				DataCache.Token, _ = generateToken(c, DataCache.User)
				util.SuccessResponse(c, DataCache)
				return
			}

		}
	}
	var account models.H_account
	if err := db.DbUser.Where("`username` = ? and `password` = ?", username, util.Sha256(password)).
		Preload("User").First(&account).Error; err != nil {
		util.FailedResponse(c, status.UsernameOrPasswordError, "用户名或密码错误")
		return
	}

	if account.User.Is_able == 0 || account.Is_able == 0 {
		util.FailedResponse(c, 10001, "用户已被删除")
		return
	}

	if account.Is_allow == 0 || account.Is_allow == 0 {
		util.FailedResponse(c, 10002, "用户已被禁用")
		return
	}
	token, _ := generateToken(c, account.User)
	data := LoginResult{
		User:     account.User,
		Token:    token,
		Password: password,
	}
	cache.Gmaps.Set(CacheKey, data)
	util.SuccessResponse(c, data)
	return
}

// 生成令牌
func generateToken(c *gin.Context, user models.H_user) (token string, err error) {
	j := jwt.JWT{
		[]byte("hignton"),
	}
	claims := jwt.CustomClaims{
		user.Id,
		user.Company_id,
		user.Role_id,
		user.Organization_id,
		jwtgo.StandardClaims{
			NotBefore: int64(time.Now().Unix()),          // 签名生效时间
			ExpiresAt: int64(time.Now().Unix() + 3600*8), // 过期时间 一小时
			Issuer:    "hignton",                         //签名的发行者
		},
	}
	token, err = j.CreateToken(claims)
	return
}

// @Summary 删除用户信息缓存
// @Description  删除指定用户信息缓存
// @Tags 权限
// @Produce  json
// @Success 200  {object} models.H_service
// @Param   username       path    string  true       "用户ID"
// @Failure 201
// @router /api/v1/Login/{username} [delete]
func DelUserCache(c *gin.Context)  {
	username := c.Param("username")
	CacheKey := username + "_user"
	cache.Gmaps.Remove(CacheKey)
	util.SuccessResponse(c, nil)
}
